//
//  BQRouter.m
//  BQNavigator
//
//  Created by Zhiqiang Bao on 15-4-3.
//  Copyright (c) 2015年 Zhiqiang Bao. All rights reserved.
//

#import "BQRouter.h"
#import <UIKit/UIKit.h>

/*--------------------  BQRouterPair  --------------------*/

@interface BQRouterPair : NSObject

@property (nonatomic, strong) BQOrder   *order;
@property (nonatomic, strong) BQRunner  *runner;

+ (BQRouterPair *)pairWithOrder:(BQOrder *)order runner:(BQRunner *)runner;

@end

@implementation BQRouterPair

+ (BQRouterPair *)pairWithOrder:(BQOrder *)order runner:(BQRunner *)runner
{
    if (order.event.length == 0 || runner == nil) return nil;
    
    BQRouterPair *pair = [[BQRouterPair alloc] init];
    
    pair.order = order;
    pair.runner = runner;
    
    return pair;
}

@end

/*--------------------    BQRouter    --------------------*/

@interface BQRouter ()

@property (nonatomic, strong) NSMutableDictionary *storeData;

@end

@implementation BQRouter

#pragma mark - init

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.storeData = [NSMutableDictionary dictionary];
    }
    return self;
}

#pragma mark - Register API

- (void)registerOrder:(BQOrder *)order toRunner:(BQRunner *)runner
{
    BQRouterPair *pair = [BQRouterPair pairWithOrder:order runner:runner];
    
    if (pair) {
        _storeData[order.event] = pair;
    }
}

- (void)mapOrder:(BQOrder *)first toOrder:(BQOrder *)second
{
    NSString *event = second.event;
    
    if (event.length > 0) {
        BQRouterPair *pair = _storeData[event];
        
        if (pair) {
            [self registerOrder:first toRunner:pair.runner];
        }
    }
}

#pragma mark - Run API

- (id)executeOrder:(BQOrder *)order withOption:(id)option
{
    return [self executeOrderEvent:order.event withOption:option];
}

- (id)executeOrderEvent:(NSString *)event withOption:(id)option
{
    id result = nil;
    
    if (event.length > 0) {
        BQRouterPair *pair = _storeData[event];
        
        if (pair) {
            result = [pair.runner runOrder:pair.order withOption:option];
        } else {
            // Unsupport/unregister event
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:event]]) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:event]];
            }
        }
    }
    
    return result;
}

- (id)executeOrder:(BQOrder *)order
{
    return [self executeOrder:order withOption:nil];
}

- (id)executeOrderEvent:(NSString *)event
{
    return [self executeOrderEvent:event withOption:nil];
}

#pragma mark - Query API

- (BQOrder *)registeredOrderByEvent:(NSString *)event
{
    if (event.length == 0) return nil;
    
    BQRouterPair *pair = _storeData[event];
    
    return pair.order;
}

- (BQRunner *)registeredRunnerByEvent:(NSString *)event
{
    if (event.length == 0) return nil;
    
    BQRouterPair *pair = _storeData[event];
    
    return pair.runner;
}

@end
